import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.MediaTracker;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.*;

class CuteCaptchaController {
	
	private static final String SOURCECHARS = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz123456789"
	
	def index = {
		response.setContentType("image/png");
		response.setHeader("Cache-control", "no-cache");

		// Generate and remember the Source Character string (6 characters)
		int l = SOURCECHARS.length();
		StringBuffer b = new StringBuffer();
		6.times {
		    int r = (int)(Math.random() * l);
		    b.append(SOURCECHARS.charAt(r));
		}

		final int height = 200;
		final int width = 200;
		final int space = 8;

		System.setProperty("java.awt.headless", "true");
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = bufferedImage.createGraphics();
		Font font = new Font("Serif", Font.BOLD, 35);
		g2d.setFont(font);
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		Rectangle2D fontRect = font.getStringBounds(b.toString(), g2d.getFontRenderContext());
		// Now, create a graphic "space" pixels wider and taller than the the font
		bufferedImage = new BufferedImage((int)fontRect.getWidth() + space,
						    (int)fontRect.getHeight() + space,
						    BufferedImage.TYPE_INT_RGB);
		g2d = bufferedImage.createGraphics();
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setFont(font);

		// Draw the background
		
		Toolkit toolkit = Toolkit.getDefaultToolkit();
//		image1 = image(file:'imagenFondo.gif')
//		MediaTracker traker = new MediaTracker(this);
		Image image1 = toolkit.getImage("imagenFondo.gif");
/*		tracker.addImage(image1);
		try {
    		//Empieza la carga de imágenes. Esperar hasta que se hayan cargado
    		tracker.waitForAll();
		} catch (InterruptedException e) {}
*/
//		image(file:'imagenFondo.gif')

		
//		ImageObserver observador = new ImageObserver();
//		image1 = toolkit.prepareImage("imagenFondo.gif",(int)fontRect.getWidth() + space,(int)fontRect.getHeight() + space, observador);

		Color micolor = new Color(90,90,220,150);
		g2d.drawImage(image1,0,0,null);

		// Draw the String
		g2d.setColor(micolor);

		g2d.drawString(b.toString(), (int)(space/2), (int)(space/4) + (int)fontRect.getHeight());
		session.setAttribute("captcha", b.toString());	
//		OutputStream out = response.getOutputStream();
		FileOutputStream out = new FileOutputStream("web-app/images/back.png"); 
		javax.imageio.ImageIO.write(bufferedImage, "PNG", out);
		out.close();
		//def session = request.getSession(true);
		
	}	
	
	def probar={}

}
